#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QNetworkDatagram>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("服务端");
    // 1.创建socket
    socket = new QUdpSocket(this);
    // 2.连接信号槽
    connect(socket, &QUdpSocket::readyRead, this, &MainWindow::processRequest);
    // 3.绑定
    bool ret = socket->bind(QHostAddress::Any, 8000);
    if (!ret)
    {
        QMessageBox::critical(nullptr, "绑定出错", socket->errorString());
        return;
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::processRequest()
{
    // 1.读取请求
    const QNetworkDatagram& requestDatagram = socket->receiveDatagram();
    QString request = requestDatagram.data();
    // 2.根据请求返回响应
    const QString& response = process(request);
    // 3.将响应发送客户端
    QNetworkDatagram responseDatagram(response.toUtf8(), requestDatagram.senderAddress()
                                      , requestDatagram.senderPort());
    socket->writeDatagram(responseDatagram);
    // 4.信息显示到列表框
    QString log = "[" + requestDatagram.senderAddress().toString() + ":"
                  + QString::number(requestDatagram.senderPort()) + "] "
                  + request;
    ui->listWidget->addItem(log);
}

QString MainWindow::process(const QString &request)
{
    // 暂时先不做处理
    return request;
}

